package com.itheima.controller;

import com.itheima.common.constant.MessageConstant;
import com.itheima.common.entity.PageResult;
import com.itheima.common.entity.QueryPageBean;
import com.itheima.common.entity.Result;
import com.itheima.common.utils.AliOssUtil;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/setmeal")
public class SetmealController {
    @Autowired
    private SetmealService setmealService;
    @Autowired
    private AliOssUtil aliOssUtil;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    @Value("${out_put_path}")//从属性文件读取输出目录的路径
    private String outputpath;

    //图片上传
    @PostMapping("/upload")
    public Result upload(MultipartFile imgFile) throws Exception {
        log.info("文件上传,{},", imgFile);

        try {
            String filename = imgFile.getOriginalFilename();//获取原始文件名

            String substring = filename.substring(filename.lastIndexOf("."));
            //生成UUid
            String url = UUID.randomUUID().toString() + substring;

            String imgUrl = aliOssUtil.upload(imgFile.getBytes(), url);
            //上传图片 缓存到 redis 缓存
            redisTemplate.opsForSet().add("imgUrl", imgUrl);

            return new Result(true, MessageConstant.PIC_UPLOAD_SUCCESS, imgUrl);

        } catch (Exception e) {
            log.info("文件上传失败");
        }
        return new Result(false, MessageConstant.PIC_UPLOAD_FAIL);
    }

    //新增体检套餐
    @PostMapping("/add")
    public Result add(@RequestBody Setmeal setmeal, @RequestParam Integer[] checkgroupIds) {
        log.info("新增套餐{},{} ", setmeal, checkgroupIds);
        setmealService.add(setmeal, checkgroupIds);

        //新增套餐后需要重新生成静态页面
        generateMobileStaticHtml();
        return new Result(true, MessageConstant.ADD_SETMEAL_SUCCESS);


    }

    //根据id查询套餐
    @GetMapping("/findById")
    public Result findById(@RequestParam Integer id) {
        log.info("根据id查询套餐 {}", id);

        return new Result(true, MessageConstant.QUERY_SETMEAL_SUCCESS, setmealService.findById(id));
    }

    //编辑套餐
    @PostMapping("/edit")
    public Result edit(@RequestBody Setmeal setmeal, @RequestParam Integer[] checkGroupIds) {
        log.info("编辑套餐{},{}", setmeal, checkGroupIds);
        setmealService.edit(setmeal, checkGroupIds);

        generateMobileStaticHtml();
        return new Result(true, MessageConstant.EDIT_SETMEAL_SUCCESS);
    }

    //查询所有套餐
    @GetMapping("/findAll")
    public Result findAll() {

        log.info("查询所有套餐");
        return new Result(true, MessageConstant.QUERY_SETMEAL_SUCCESS, setmealService.findAll());
    }


    //分页条件查询
    @PostMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPage) {
        log.info("分页条件查询套餐,{}", queryPage);
        return setmealService.findPage(queryPage);
    }


    //生成静态页面
    public void generateMobileStaticHtml() {
        //准备模板文件中所需的数据
        List<Setmeal> setmealList = (List<Setmeal>) this.findAll().getData();
        //生成套餐列表静态页面
        generateMobileSetmealListHtml(setmealList);
        //生成套餐详情静态页面（多个）
        generateMobileSetmealDetailHtml(setmealList);
    }

    //生成套餐列表静态页面
    public void generateMobileSetmealListHtml(List<Setmeal> setmealList) {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        dataMap.put("setmealList", setmealList);
        this.generateHtml("mobile_setmeal.ftl", "m_setmeal.html", dataMap);
    }

    //生成套餐详情静态页面（多个）
    public void generateMobileSetmealDetailHtml(List<Setmeal> setmealList) {
        for (Setmeal setmeal : setmealList) {
            Map<String, Object> dataMap = new HashMap<String, Object>();
            dataMap.put("setmeal", this.findById(setmeal.getId()).getData());
            this.generateHtml("mobile_setmeal_detail.ftl",
                    "setmeal_detail_" + setmeal.getId() + ".html",
                    dataMap);
        }
    }

    public void generateHtml(String templateName, String htmlPageName, Map<String, Object> dataMap) {
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        Writer out = null;
        try {
            // 加载模版文件
            Template template = configuration.getTemplate(templateName);
            // 生成数据
            File docFile = new File(outputpath + "\\" + htmlPageName);
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(docFile)));
            // 输出文件
            template.process(dataMap, out);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != out) {
                    out.flush();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
    }
}

